package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;
import com.webserver.controller.ArticleController;
import com.webserver.controller.ToolsController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 用来完成处理请求的环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) {
//        String path = request.getUri();//不再适用,因为当抽象路径含有参数时,参数的值是不固定的
        String path = request.getRequestURI();
        System.out.println("请求的抽象路径:" + path);
        //首先判断是否为请求一个业务处理
        try {
            HandlerMapping.MethodMapping mm = HandlerMapping.getMethod(path);
            if (mm!= null){
                Object controller = mm.getController();
                Method method = mm.getMethod();
                method.invoke(controller,request,response);
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
    }
        File file = new File("./webapps" + path);
        if (file.isFile()) {//请求的是一个存在的文件
            response.setContentFile(file);
        } else {
            response.setStatusCode(404);
            response.setStatusReason("Not Found");
            file = new File("./webapps/root/404.html");
            response.setContentFile(file);
        }
        response.addHeader("Server", "WebServer");
    }
}
